#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import random
from selenium import webdriver

from config import IMG_DIR
_browser = None


def get_browser():
    global _browser
    if not _browser:
        return init_browser()
    else:
        return _browser


def init_browser():
    print('init browser')
    global _browser
    try:
        _browser = webdriver.Chrome()
        _browser.implicitly_wait(30)
        return _browser
    except Exception:
        return None


def destroy_browser():
    try:
        if _browser:
            _browser.quit()
    except Exception:
        pass


def get_img():
    filelist = os.listdir(IMG_DIR)
    filename = random.choice(filelist)
    return os.path.join(IMG_DIR, filename)
